<?php
namespace App\Wen\Utils;

use App\Http\Controllers\Api\BaseController;
use App\Http\Controllers\Api\Repositories\WxSyncRelationRepositories;
use App\Http\Controllers\Api\Repositories\WxUserRepositores;
use App\Jobs\AppPushJob;
use App\Jobs\TempleteMessageJob;
use App\Jobs\UserInputSafeCheckJob;
use App\Lib\Uploads\UploadHandler;
use App\Lib\WeApp\WeApp;
use App\Models\Bureau\WxClubTeam;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\User\WxUserCoinRecord;
use App\Models\WxAttachment;
use App\Models\WxExceptional;
use App\Models\WxMinicode;
use App\Models\WxOrder;
use App\Models\Shop\WxShopOrder;
use App\Models\WxTask;
use App\Models\User\WxUser;
use App\Models\User\WxUserFollow;
use App\Models\User\WxUserLuckDrawRecord;
use App\Models\User\WxUserSignRecord;
use App\Models\User\WxUserTask;
use App\Models\WxTenant;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\UploadedFile;
use Intervention\Image\Facades\Image;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\PhoneNumber;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class Utils
{

    public static $img_style = null;
    public static $admin_auth_map = null;
    public static $admin_content_source1 = null;

    public static function msectime()
    {
        list($tmp1, $tmp2) = explode(' ', microtime());
        return sprintf('%.0f', (floatval($tmp1) + floatval($tmp2)) * 1000);
    }
    /**
     * 生成编号
     * @param $type
     * @return string
     */
    public static function getSn($type)
    {
        switch ($type) {
            case 1:         //订单编号
                $str = $type . substr(self::msectime() . rand(0, 9), 1);
                break;
            case 2:         //支付单编号
                $str = $type . substr(self::msectime() . rand(0, 9), 1);
                break;
            case 3:         //商品编号
                $str = 'G' . substr(self::msectime() . rand(0, 5), 1);
                break;
            case 4:         //货品编号
                $str = 'P' . substr(self::msectime() . rand(0, 5), 1);
                break;
            case 5:         //售后单编号
                $str = $type . substr(self::msectime() . rand(0, 9), 1);
                break;
            case 6:         //退款单编号
                $str = $type . substr(self::msectime() . rand(0, 9), 1);
                break;
            case 7:         //退货单编号
                $str = $type . substr(self::msectime() . rand(0, 9), 1);
                break;
            case 8:         //发货单编号
                $str = $type . substr(self::msectime() . rand(0, 9), 1);
                break;
            case 9:         //提货单号
                $chars    = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '2', '3', '4', '5', '6', '7', '8', '9'];
                $charsLen = count($chars) - 1;
                shuffle($chars);
                $str = '';
                for ($i = 0; $i < 6; $i++) {
                    $str .= $chars[mt_rand(0, $charsLen)];
                }
                break;
            case 10: // 激励视频code
                $str = $type . substr(self::msectime() . rand(0, 9), 2);
                break;
            case 11: // 授权唯一值
                $str = $type . substr(self::msectime() . rand(0, 9), 2);
                break;
            case 12: // 扫码劵code
                $str = $type . substr(self::msectime() . rand(0, 9), 4);
                break;
            case 13: // 商户退款单号
                $str = 'R' . substr(self::msectime() . rand(0, 9), 1);
                break;
            case 14: // 提现单号
                $str = 'W' . substr(self::msectime() . rand(0, 9), 1);
                break;
            default:
                $str = substr(self::msectime() . rand(0, 9), 1);
        }
        return $str;
    }
    /**
     * @param $url 图片地址
     * @param $num 调用样式几
     */
    public static function imgWithStyle($url, $num = 0, $is_arr = false, $is_remove_style = false){
        if(_empty_($url)){
            return null;
        }
        if(self::$img_style === null){
            $style_action = Settings::get('img_style_action', 1);
            if($style_action == 2){
                $img_style = Settings::get('img_style', []);
                if(_empty_($img_style)){
                    self::$img_style = [];
                    return $url;
                }
                self::$img_style = [];
                foreach ($img_style as $style){
                    self::$img_style[$style['domain']] = explode(',',  $style['style'] ?: '' );
                }
            }else if($style_action == 1){
                self::$img_style['*'] = ['?imageMogr2/format/webp/interlace/1', '?imageMogr2/thumbnail/300x/format/webp/interlace/1', '?imageMogr2/thumbnail/50x50/crop/50x50/gravity/center/format/webp/interlace/1/quality/100', ''];
            }else{
                self::$img_style = [];
            }
        }
        if($is_remove_style){
            foreach (self::$img_style as $key => $styles){
                if($key == '*' || strpos($url, $key) === 0){
                    if(self::$img_style[$key]){
                        foreach (self::$img_style[$key] as $style_name){
                            $url = str_replace($style_name, '', $url);
                        }
                    }
                }
            }
            $position = strpos($url, '?imageMo');
            if ($position !== false) {
                $url = substr($url, 0, $position);
            }
            return $url;
        }else{
            if(StrUtils::endsWith($url, '.gif')){
                return $url;
            }
            if($num < 0){
                return $url;
            }
            if($is_arr){
                $url_arr = [];
                if(!$url){
                    return $url_arr;
                }
                foreach ($url as $url_){
                    $url_arr[] = self::imgWithStyle($url_, $num);
                }
                return $url_arr;
            }else{
                foreach (self::$img_style as $key => $styles){
                    if($key == '*' || strpos($url, $key) === 0){
                        return $url. (self::$img_style[$key][$num] ?? '' );
                    }
                }
                return $url;
            }
        }
    }

    /**
     * 初始化配置同步数据
     */
    private static function _initSyncCmsMap(){

        if(self::$admin_auth_map === null){
            $admin_auth_map = Settings::get('admin_auth_map', []);
            self::$admin_auth_map = [];
            foreach ($admin_auth_map as $map){
                self::$admin_auth_map[$map['id']] = $map;
            }
        }

        if(self::$admin_content_source1 === null){
            self::$admin_content_source1 = Settings::get('admin_content_source1', []);
        }
    }

    /**
     * 获取对应域名的映射组
     * @param $domain
     * @return array|mixed
     */
    public static function getSyncCmsMap($domain){

        self::_initSyncCmsMap();

        if(_empty_(self::$admin_content_source1) || _empty_(self::$admin_auth_map)){
            return [];
        }

        foreach (self::$admin_content_source1 as $key=>$source){
            if(strpos($source['url'], $domain) !== false){
                if($source['needSync'] == '0'){
                    return [];
                }
                if(!isset(self::$admin_auth_map[$source['map']])){
                    return [];
                }
                return self::$admin_auth_map[$source['map']];
            }
        }
        return [];
    }

    /** 根据圈子id，或者商品分类id，获取需要同步其他cms的一个列表
     * @param $circle_id ms圈子 id
     * @param $good_class_id ms商品分类id
     * return [['url'=>'','class' => classid,'type' => 'post|goods'],]
     */
    public static function syncCmsUrls($uid, $circle_id, $good_class_id = 0){

        self::_initSyncCmsMap();
        // 同步文章
        if(_empty_(self::$admin_content_source1) || _empty_(self::$admin_auth_map)){
            return [];
        }

        if($circle_id){

            $res = [];
            foreach (self::$admin_content_source1 as $key=>$source){
                if($source['needSync'] == '0'){
                    continue;
                }
                if(!isset(self::$admin_auth_map[$source['map']])){
                    continue;
                }
                $circleMap = self::$admin_auth_map[$source['map']]['circleMap'];
                if(isset($circleMap[$circle_id])){
                    $external_uid = WxSyncRelationRepositories::uid(parse_url($source['url'], PHP_URL_HOST), $uid);
                    $res[] = [
                        'url'=>$source['url'].'/wp-content/module/public/function/minisns-master-sync/acept.php?'.$source['safe'],
                        'class' => $circleMap[$circle_id],
                        'type' => 'post',
                        'uid' => $external_uid,
                        'userData' => _empty_($external_uid) ? WxUserRepositores::userData($uid) : []
                    ];
                }
            }
            return $res;

        }else if($good_class_id){
            // 同步商品
            $res = [];
            foreach (self::$admin_content_source1 as $key=>$source){
                if($source['needSync'] == '0'){
                    continue;
                }
                if(!isset(self::$admin_auth_map[$source['map']])){
                    continue;
                }
                $goodsClassMap = self::$admin_auth_map[$source['map']]['goodsClassMap'];
                if(isset($goodsClassMap[$good_class_id])){
                    $external_uid = WxSyncRelationRepositories::uid(parse_url($source['url'], PHP_URL_HOST), $uid);
                    $res[] = [
                        'url'=>$source['url'].'/wp-content/module/public/function/minisns-master-sync/acept.php?'.$source['safe'],
                        'class' => $goodsClassMap[$good_class_id],
                        'type' => 'goods',
                        'uid' => WxSyncRelationRepositories::uid(parse_url($source['url'], PHP_URL_HOST), $uid),
                        'userData' => _empty_($external_uid) ? WxUserRepositores::userData($uid) : []
                    ];
                }
            }
            return $res;
        }
        return [];
    }

    /** 用于支付时拼接完整的html，或者返回已经缓存的html
     * @param $out_trade_no
     * @param string $inner_form
     * @return mixed|string
     */
    static function payDirectHtmlForApp($out_trade_no, $inner_form = '', $success = false){
        if($success){
            return '<!DOCTYPE html> <html> <head> <title>支付成功</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui"> <style type="text/css"> body { text-align: center; } h1 { color: #4caf50; } </style> </head> <body> <h1>支付成功</h1><p>订单号：'.self::outTradeNoPre($out_trade_no, '').'</p> </body> </html>';
        }else{
            if($out_trade_no){
                return Cache::get($out_trade_no, '<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>订单url已过期</title> </head> <body>订单url已过期，请重新发起支付 </body> </html>');
            }else{
                return '<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Redirecting</title> </head> <body> '.$inner_form.'</body> </html>';
            }
        }
    }

    /** 为app生成临时可用户查询订单状态的id
     * @param $out_trade_no
     * @param string $platform
     * @return array|string|string[]
     */
    static function outTradeNoPre($out_trade_no, $platform = 'wx_order_'){
        if(_empty_($platform)){
            return str_replace(['wx_order_', 'ali_order_', 'yi_order_' ,'wx_shoporder_', 'ali_shoporder_', 'yi_shoporder_'], '', $out_trade_no);
        }else{
            return $platform.$out_trade_no;
        }
    }

    /** 处理 yyyyMMddHHmmss 格式时间字符串
     * @param $yyyyMMddHHmmss
     * @return array|string|string[]|null
     */
    static function strTimeFormat( $yyyyMMddHHmmss ){
        return preg_replace('{^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(.*?)$}u', '$1-$2-$3 $4:$5:$6', $yyyyMMddHHmmss);
    }


    /** 生成小程序码
     * @param $page
     * @param $scene
     * @return string
     */
    static function getMiniCode($page, $scene, $user_id = 0, $width = 430, $auto_color = false, $line_color = null, $is_hyaline = false, $env_version = 'release'){
        $page = ltrim(_empty_default_($page, ''), '/');
        if(_empty_($page) || (_empty_($scene) && _empty_($user_id))){
            return Settings::get('app_mini_code');
        }
        global $__MINI_GLOBAL_TENANT_ID__;
        if(strlen($scene) > 31){
            if($user_id === 0){
                return Settings::get('app_mini_code');
            }else{
                UserInputSafeCheckJob::dispatch($user_id, $page.$scene);
            }
        }
        if(_empty_($user_id) || $user_id <= 0){
            $user_id = 0;
        }
        $app_id = Settings::get('app_id');
        $last_scene = $scene . ($user_id > 0 ? ( (_empty_($scene) ? '' : '&') . 'from_user=' . $user_id ) : '');
        if($__MINI_GLOBAL_TENANT_ID__ > 0){
//            $last_scene = $last_scene . ($__MINI_GLOBAL_TENANT_ID__ > 0 ? (( _empty_($last_scene) ? '' : '&' ) . 'tenant=' . $__MINI_GLOBAL_TENANT_ID__) : '');
        }

        if(_empty_($app_id)){
            $app_h5_home = Settings::get('app_h5_home');
            if($app_h5_home){
                $last_scene = _encodeURIComponent($last_scene);
                $url = $app_h5_home. '/#/'.$page.'?scene='.$last_scene;
                return 'data:image/png;base64,'.base64_encode(QrCode::format('png')->size(200)->generate($url));
            }else{
                return Settings::get('app_mini_code');
            }
        }

        $fake_scene = $scene;
        if($is_hyaline){
            $fake_scene .= '|hyaline';
        }
        if($env_version == 'release'){
            $WxMinicode = WxMinicode::where([
                ['app_id', '=', $app_id],
                ['path', '=', $page],
                ['scene', '=', $fake_scene],
                ['user_id', '=', $user_id]
            ])->first();
            if($WxMinicode){
                return $WxMinicode->code;
            }
        }

//        $cache_key = 'minicode:'.$app_id.':'.$page.':'.$scene;
        try {
            $weapp = new WeApp();
            //从‘小程序’获取一个‘二维码’单例对象
            $qrcode = $weapp->getQRCode();
            //2.获取小程序B码
            $qrcodeContent = $qrcode->getQRCodeB($last_scene, $page, $width, $auto_color, $line_color, $is_hyaline, $env_version);
            $file_name = md5(uniqid()) . '.png';
            $filePath = 'qrcode/' . $file_name;
            // 3.上传B码
            if ($qrcodeContent) {
                $img = Image::make($qrcodeContent);
                $img->save(public_path('storage/'.$filePath), 100);

                $cos_res = UploadHandler::handle(new UploadedFile(public_path('storage/'.$filePath), $file_name));
                if(_array_key($cos_res, 'url', null)){

                    if($env_version == 'release'){
                        $new_WxMinicode = new WxMinicode();
                        $new_WxMinicode->app_id = $app_id;
                        $new_WxMinicode->path = $page;
                        $new_WxMinicode->scene = $fake_scene;
                        $new_WxMinicode->user_id = $user_id;
                        $new_WxMinicode->code = $cos_res['url'];
                        $new_WxMinicode->save();
                    }

                    @unlink(public_path('storage/'.$filePath));
                    return $cos_res['url'];
                }

            }else{
                return '';
            }
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage());
        }
        return Settings::get('app_mini_code');
    }




    public static function getStylesList()
    {
        $img_styles = json_decode(Settings::get('img_style', ''), true);
    }



    /*
     * 不强制登录时，获取id
     */
    public static function uid(Request $request){
        return $request->uid;
    }

    /**
     * @param $title
     * @param $content
     * @param $mode
     * @param $data
     * @param string $way single|all|batch
     * @param array $cids
     * @param false $receive_handle 0: 不响应 1：正常响应 2：创建推送
     * @param bool $click_handle
     */
    public static function app_push($title, $content, $mode, $data, $way = 'all', $uids = [], $receive_handle = 0, $asyn = true){
        $title = strip_tags($title);
        $content = strip_tags($content);
        $cids = [];
        if($uids){
            if(is_array($uids)){
                foreach ($uids as $uid){
                    $push_client_id = WxUser::where('id', $uid)->value('push_client_id');
                    if($push_client_id){
                        $cids[] = $push_client_id;
                    }
                }
            }
        }
        $payload = GatewayUtils::message_arr($mode, $data);
        $payload['response_receive'] = $receive_handle;

        if($asyn){
            AppPushJob::dispatch($title, $content, $payload, $cids, $way);
            return 1;
        }else{
            return GatewayUtils::app_push($title, $content, $payload, $cids, $way);
        }
    }

    public static function templateMessage($uid, $title, $key1, $key2, $key3, $remark = '', $type = 'notice', $online_force = false){
        global $__MINI_GLOBAL_PAYCODE_2__;
        if(!$__MINI_GLOBAL_PAYCODE_2__){
            return null;
        }
        if($uid == 'admin'){
            $users_id = explode(',', Settings::get('app_admin_super_admin', '', true));
            if(_empty_($users_id)){
                return null;
            }
            $uid = $users_id[0];
        }else{
            if(!$online_force){
                if(UserUtils::is_user_online($uid, 1)){
                    return null;
                }
            }
        }

        try{
            $title = StrUtils::limit(strip_tags($title ?? ''));
            $key1 = StrUtils::limit(strip_tags($key1 ?? ''));
            $key2 = StrUtils::limit(strip_tags($key2 ?? ''));
            $key3 = StrUtils::limit(strip_tags($key3 ?? ''));
            if($type == 'notice'){
                $templateId = Settings::get('template_message_notice_id');
            }else{
                return null;
            }
            if(_empty_($templateId)){
                return null;
            }

            $userOpenID = WxUser::where('id', $uid)->value('weixin_mp_openid');
            if(_empty_($userOpenID)){
                return null;
            }


            $data=array(
                'first'=>array('value'=>$title,'color'=>"#FF0000"),
                'keyword1'=>array('value'=>$key1,'color'=>'#999999'),
                'keyword2'=>array('value'=>$key2,'color'=>'#FF0000'),
                'keyword3'=>array('value'=>$key3,'color'=>'#FF0000'),
                'remark' =>array('value'=>StrUtils::limit($remark),'color'=>'#999999'),
                'time33' => [
                    'value' => strpos($key2, '202') === 0 ? $key2 : date('Y年m月d日 H:i', time()),
                ],
                'thing19' => [
                    'value' => $title,
                ],
                'thing6' => [
                    'value' => $key1,
                ]
            );

            TempleteMessageJob::dispatch([
                'touser' => $userOpenID,
                'template_id' => $templateId,
                'miniprogram' => [
                    'appid' => Settings::get('app_id'),
                    'pagepath' => 'pages/tabbar/notice/notice',
                ],
                'data' => $data,
            ]);

            return true;
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage());
            return false;
        }
    }

    public static function isImgUrl($url){
        return preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $url);
    }

    public static function getDecayCoefficient($x, $rate = 10){
        $b = floor($x / $rate);
        if($b >= 300){
            return 0.01;
        }else if($b >= 100){
            return 0.1;
        }else if($b >= 10){
            return 0.2;
        }else if($b >= 5){
            return 0.3;
        }else if($b >= 2){
            return 0.5;
        }else if($b >= 1){
            return 0.8;
        }else{
            return 1;
        }
    }

    public static function getWeekDays($time = '', $format='Y-m-d H:i:s'){
        $time = $time != '' ? $time : time();
        //获取当前周几
        $week = date('w', $time);
        $date = [];
        if(_empty_($week)){
            $week = 7;
        }
        for ($i=0; $i< 7; $i++){
            $date[$i] = date($format ,strtotime( '+' . ($i+1-$week) .' days', $time));
        }
        return $date;
    }

    public static function isTaskComplete($user_id, $task_id, $check = false){
        $res = ['code' => -1, 'current'=>0, 'condition'=>0];
        if(_empty_($user_id) || _empty_($task_id)){
            return $res;
        }
        $task = WxTask::find($task_id);
        if(!$task){
            return $res;
        }
        $type = $task->type;
        if($type == 1){
            $condition_type = $task->condition_type_1;
        }else{
            $condition_type = $task->condition_type_0;
        }
        $condition_num = $task->condition_num;
        $res['condition'] = $task->condition_num;
        if(!$check){
            if($type == 0){
                if(WxUserTask::where([
                    ['user_id', '=', $user_id],
                    ['task_id', '=', $task_id],
                    ['created_at', 'like', '%' . date("Y-m-d", time()) . '%']
                ])->exists()){
                    $res['code'] = 1;
                    return $res;
                }else{
                    $res['code'] = 0;
                    return $res;
                }
            }else{
                if(WxUserTask::where([
                    ['user_id', '=', $user_id],
                    ['task_id', '=', $task_id]
                ])->exists()){
                    $res['code'] = 1;
                    return $res;
                }else{
                    $res['code'] = 0;
                    return $res;
                }
            }
        }else{
            $c = self::CompleteCondition($user_id, $type, $condition_type, $condition_num);
            $res['current'] = $c;
            if($c == $condition_num){
                $res['code'] = 1;
            }else{
                $res['code'] = 0;
            }
            return $res;
        }
    }

    public static function CompleteCondition($user_id, $type, $condition_type, $condition_num){
        if($type == 0){
            if($condition_type == 0){
                // 每日签到
                return UserUtils::is_signed($user_id) ? 1 : 0;
            }else if($condition_type == 1){
                // 每日抽奖
                return WxUserLuckDrawRecord::where('user_id', $user_id)
                    ->where('created_at', 'like', '%' . date("Y-m-d", time()) . '%')
                    ->count();
            }else if($condition_type == 2){
                // 每日登录
                if($user_id > 0){
                    return 1;
                }
                return 0;
            }else if($condition_type == 3){
                // 发布内容
                return WxPost::where('user_id', $user_id)
                    ->where('created_at', 'like', '%' . date("Y-m-d", time()) . '%')
                    ->count();
            }else if($condition_type == 4){
                // 评论内容
                return WxComment::where('user_id', $user_id)
                    ->where('created_at', 'like', '%' . date("Y-m-d", time()) . '%')
                    ->count();
            }else if($condition_type == 5){
                // 喜欢内容
                return WxLike::where('user_id', $user_id)
                    ->where('created_at', 'like', '%' . date("Y-m-d", time()) . '%')
                    ->count();
            }else if($condition_type == 6){
                // 充电内容
                return WxExceptional::where('user_id', $user_id)->where('posts_user_id', '<>', $user_id)
                    ->where('created_at', 'like', '%' . date("Y-m-d", time()) . '%')
                    ->count();
            }else if($condition_type == 7){

            }else if($condition_type == 8){
                return WxUser::where('who', $user_id)
                    ->where('created_at', 'like', '%' . date("Y-m-d", time()) . '%')
                    ->count();
            }else if($condition_type == 9){
                // 每日激励次数
                return WxUserCoinRecord::where([
                    ['user_id', '=', $user_id],
                    ['type', '=', 10],
                    ['created_at', '>=', Carbon::today()]
                ])->count();
            }
        }else if($type == 1){
            if($condition_type == 0){
                // 认证用户
                $is_authentication = WxUser::where('id', $user_id)->value('is_authentication');
                if($is_authentication){
                    return 1;
                }
                return 0;
            }else if($condition_type == 1){
                // App登录
                $weixin_app_openid = WxUser::where('id', $user_id)->value('weixin_app_openid');
                if($weixin_app_openid){
                    return 1;
                }
                return 0;
            }else if($condition_type == 2){
                // 签到总次数
                return WxUserSignRecord::where('user_id', $user_id)->count();
            }else if($condition_type == 3){
                // 抽奖总次数
                return WxUserLuckDrawRecord::where('user_id', $user_id)->count();
            }else if($condition_type == 4){
                // 拥有签名
                $user_introduce = WxUser::where('id', $user_id)->value('user_introduce');
                if($user_introduce){
                    return 1;
                }
                return 0;
            }else if($condition_type == 5){
                // 发表内容数
                return WxPost::where('user_id', $user_id)->count();
            }else if($condition_type == 6){
                // 评论数
                return WxComment::where('user_id', $user_id)->count();
            }else if($condition_type == 7){
                // 喜欢内容
                return WxLike::where('user_id', $user_id)->count();
            }else if($condition_type == 8){
                // 内容被喜欢
                return WxLike::where('posts_user_id', $user_id)->count();
            }else if($condition_type == 9){
                // 粉丝量
                return WxUserFollow::where('user_follow_id', $user_id)->count();
            }else if($condition_type == 10){
                // 使用小程序
                $weixin_openid = WxUser::where('id', $user_id)->value('weixin_openid');
                if($weixin_openid){
                    return 1;
                }
                return 0;
            }else if($condition_type == 11){
                // 充电总额
                return WxExceptional::where('user_id', $user_id)->where('posts_user_id', '<>', $user_id)->sum('exceptional_price');
            }else if($condition_type == 12){
                // 被充电总额
                return WxExceptional::where('posts_user_id', $user_id)->where('user_id', '<>', $user_id)->sum('exceptional_price');
            }else if($condition_type == 13){
                // 拥有金币
                return UserUtils::user_coins($user_id);
            }else if($condition_type == 14){
                // 成为Vip
                $is_member = WxUser::where('id', $user_id)->value('is_member');
                if($is_member){
                    return 1;
                }
                return 0;
            }else if($condition_type == 15){
                return 0;
            }else if($condition_type == 16){
                return 0;
            }else if($condition_type == 17){
                // 完成任务数量
                return WxUserTask::where('user_id', $user_id)->count();
            }else if($condition_type == 18){
                // 完成任务数量
                return WxUser::where('who', $user_id)->count();
            }else if($condition_type == 19){
                if($user_id > 0){
                    return 1;
                }
                return 0;
            }else if($condition_type == 20){
                return WxUserCoinRecord::where([
                    ['user_id', '=', $user_id],
                    ['type', '=', 10]
                ])->count();
            }else if($condition_type == 20){
                return WxClubTeam::where('type', 2)->where('is_lock', 1)->where('members', 'like', "%'".$user_id."'%")->count();
            }
        }

        return 0;
    }


    public static function sendSMS($iddcode, $phone, $code, $ttl = 60, $cache_key = ''){
        $resp = [
            'code' => 0,
            'msg' => ''
        ];
        $platform = Settings::get('app_sms_platform', 0);
        try{
            $number = new PhoneNumber($phone, $iddcode);
            if($platform == 0){
                $cosConfig = Settings::get('cosv5', []);
                $secret_id = $cosConfig['secretId'];
                $secret_key = $cosConfig['secretKey'];
                $app_sms_tecent_secretId = Settings::get('app_sms_tecent_secretId', '');
                if(!_empty_($app_sms_tecent_secretId)){
                    $secret_id = $app_sms_tecent_secretId;
                    $secret_key = Settings::get('app_sms_tecent_secretKey', '');
                }

                $config = [
                    // HTTP 请求的超时时间（秒）
                    'timeout' => 5.0,
                    // 默认发送配置
                    'default' => [
                        // 网关调用策略，默认：顺序调用
                        'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
                        // 默认可用的发送网关
                        'gateways' => [
                            'qcloud',
                        ],
                    ],
                    // 可用的网关配置
                    'gateways' => [
                        'errorlog' => [
                            'file' => storage_path('logs/sms.log'),
                        ],
                        'qcloud' => [
                            'sdk_app_id' => Settings::get('app_sms_tecent_appid', ''), // 短信应用的 SDK APP ID
                            'secret_id' => $secret_id, // SECRET ID
                            'secret_key' => $secret_key, // SECRET KEY
                            'sign_name' => $iddcode !=86 ? Settings::get('app_sms_tecent_out_sign_content', '') : Settings::get('app_sms_tecent_sign_content'), // 短信签名
                        ],
                    ],
                ];
                $easySms = new EasySms($config);
                $easySms->send($number, [
                    'content'  => '您的'.Settings::get('app_name', '').'验证码为: '.$code,
                    'template' => $iddcode !=86 ? Settings::get('app_sms_tecent_out_template_id', '') : Settings::get('app_sms_tecent_template_id', ''),
                    'data' => [
                        'code' => $code
                    ],
                ]);
            }else if($platform == 1){
                if($iddcode != 86){
                    $config = [
                        // HTTP 请求的超时时间（秒）
                        'timeout' => 5.0,
                        // 默认发送配置
                        'default' => [
                            // 网关调用策略，默认：顺序调用
                            'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
                            // 默认可用的发送网关
                            'gateways' => [
                                'AliyunIntl',
                            ],
                        ],
                        // 可用的网关配置
                        'gateways' => [
                            'errorlog' => [
                                'file' => storage_path('logs/sms.log'),
                            ],
                            'AliyunIntl' => [
                                'access_key_id' => Settings::get('app_sms_aliyun_secretId', ''), // SECRET ID
                                'access_key_secret' => Settings::get('app_sms_aliyun_secretKey', ''), // SECRET KEY
                                'sign_name' => Settings::get('app_sms_aliyun_sign_name'), // 短信签名
                            ],
                        ],
                    ];
                }else{
                    $config = [
                        // HTTP 请求的超时时间（秒）
                        'timeout' => 5.0,
                        // 默认发送配置
                        'default' => [
                            // 网关调用策略，默认：顺序调用
                            'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
                            // 默认可用的发送网关
                            'gateways' => [
                                'aliyun',
                            ],
                        ],
                        // 可用的网关配置
                        'gateways' => [
                            'errorlog' => [
                                'file' => storage_path('logs/sms.log'),
                            ],
                            'aliyun' => [
                                'access_key_id' => Settings::get('app_sms_aliyun_secretId', ''), // SECRET ID
                                'access_key_secret' => Settings::get('app_sms_aliyun_secretKey', ''), // SECRET KEY
                                'sign_name' => Settings::get('app_sms_aliyun_sign_name'), // 短信签名
                            ]
                        ],
                    ];
                }
                $easySms = new EasySms($config);
                $easySms->send($number, [
                    'content'  => '您的'.Settings::get('app_name', '').'验证码为: '.$code,
                    'template' => $iddcode != 86 ? Settings::get('app_sms_aliyun_out_template_id', '') : Settings::get('app_sms_aliyun_template_id', ''),
                    'data' => [
                        'code' => $code
                    ],
                ]);
            }else if($platform == 2){
                $config = [
                    // HTTP 请求的超时时间（秒）
                    'timeout' => 5.0,
                    // 默认发送配置
                    'default' => [
                        // 网关调用策略，默认：顺序调用
                        'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
                        // 默认可用的发送网关
                        'gateways' => [
                            'smsbao',
                        ],
                    ],
                    // 可用的网关配置
                    'gateways' => [
                        'errorlog' => [
                            'file' => storage_path('logs/sms.log'),
                        ],
                        'smsbao' => [
                            'user' => Settings::get('app_sms_smsbao_username', ''), // SECRET ID
                            'password' => Settings::get('app_sms_smsbao_password', ''), // SECRET KEY
                        ],
                    ],
                ];
                $easySms = new EasySms($config);
                $easySms->send($number, [
                    'content'  => '【'.Settings::get('app_sms_smsbao_sign', '宠也').'】您的'.Settings::get('app_name', '').'验证码为: '.$code,
                ]);
            }

            if($cache_key){
                Cache::forget(md5($cache_key));
                Cache::put(md5($cache_key), $code, $ttl);
            }
            $resp['code'] = 200;
            return $resp;
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getExceptions());
            // {"qcloud":{"raw":{"Response":{"SendStatusSet":[{"SerialNo":"","PhoneNumber":"+8613399770670","Fee":0,"SessionContext":"","Code":"LimitExceeded.PhoneNumberDailyLimit","Message":"the number of sms messages sent from a single mobile number every day exceeds the upper limit","IsoCode":"CN"}],"RequestId":"6b3074f6-4cd9-4531-9585-b4a25e353ce8"}}}}
            if($platform == 0){
                $exceptions = $e->getExceptions();
                if(is_string($exceptions)){
                    $exceptions = json_decode($exceptions, true);
                }else if(is_array($exceptions)){

                }
                if(is_array($exceptions)){
                    $qcloud = _array_key($exceptions, 'qcloud', []);
                    if(is_array($qcloud) && count($qcloud) > 0){
                        $raw = _array_key($qcloud, 'raw', []);
                        if(is_array($raw) && count($raw) > 0){
                            $Response= _array_key($raw, 'Response', []);
                            if(is_array($Response) && count($Response) > 0){
                                $SendStatusSet= _array_key($Response, 'SendStatusSet', []);
                                if(is_array($SendStatusSet) && count($SendStatusSet) > 0){
                                    $Message = _array_key($SendStatusSet, 'Message', '');
                                    if(!_empty_($Message)){
                                        $resp['msg'] = $Message;
                                        return $resp;
                                    }

                                }
                            }
                        }
                    }
                }
            }
            return $resp;
        }
    }

    public static function get_online_tenants(){
        $is_multi_site = Settings::get('is_multi_site', 0);
        if($is_multi_site > 0){
            $query = WxTenant::where('status', 0);
            if($is_multi_site == 1){
                $query = $query->where('tenant_id', '!=', 999);
            }else if($is_multi_site == 2){

            }else if($is_multi_site == 3){
                $query = $query->where('tenant_id', '!=', 0)->where('tenant_id', '!=', 999);
            }else{
                $query = $query->where('tenant_id', 0);
            }
            $tenants = $query->orderBy('order', 'desc')->orderBy('tenant_id', 'desc')->limit(10)->get();
            if($tenants){
                $tenants->map(function ($v){
                    global $__MINI_GLOBAL_TENANTS_ARR__;
                    if(in_array($v->tenant_id, $__MINI_GLOBAL_TENANTS_ARR__)){
                        $v->auth = true;
                    }else{
                        $v->auth = false;
                    }
                    return $v;
                });
            }

            return $tenants;
        }
        return [];
    }

    /*
     * $flag 1:登录 0：注册
     */
    public static function get_login_styles($flag = 1){
        global $__MINI_GLOBAL_DEVICE__,$__MINI_GLOBAL_PLATFORM__;
        if($flag === 1){
            if($__MINI_GLOBAL_DEVICE__ == 'mp'){
                return Settings::get('app_login_style', [0]);
            }else if($__MINI_GLOBAL_DEVICE__ == 'h5'){
                return Settings::get('app_h5_login_style', [0]);
            }else if($__MINI_GLOBAL_DEVICE__ == 'app'){
                if($__MINI_GLOBAL_PLATFORM__ == 'android'){
                    return Settings::get('app_app_android_login_style', [0]);
                }else{
                    return Settings::get('app_app_ios_login_style', [0]);
                }
            }else{
                // pc端
                return [0, 1, 2, 3, 4];
            }
        }else if($flag === 0){
            if($__MINI_GLOBAL_DEVICE__ == 'mp'){
                return Settings::get('app_register_style', [0]);
            }else if($__MINI_GLOBAL_DEVICE__ == 'h5'){
                return Settings::get('app_h5_register_style', [0]);
            }else if($__MINI_GLOBAL_DEVICE__ == 'app'){
                if($__MINI_GLOBAL_PLATFORM__ == 'android'){
                    return Settings::get('app_app_android_register_style', [0]);
                }else{
                    return Settings::get('app_app_ios_register_style', [0]);
                }
            }else{
                // pc端
                return [0, 1, 2, 3, 4];
            }
        }
    }

    public static function image_state_change($images, $state = 1){
        if(_empty_($images)){
            return;
        }
        foreach ($images as $url) {
            if(_empty_($url)){
                continue;
            }
            $attachment_part = FileUtils::get_attachment_part_from_url($url);
            if ($attachment_part) {

                if($state == 1){
                    WxAttachment::where([
                        ['domain', '=', $attachment_part['domain']],['path', '=', $attachment_part['path']],['state', '=', 0]
                    ])->update(['state' => 1]);
                }else if($state == 0){
                    WxAttachment::where([
                        ['domain', '=', $attachment_part['domain']],['path', '=', $attachment_part['path']],['state', '=', 1]
                    ])->update(['state' => 0]);
                }

            }
        }
    }

}
